package com.wswy.wzcx.ui.njdb

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Space
import android.widget.TextView
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.ui.VOMessage
import com.che.libcommon.ui.loading.ILoadingView
import com.che.libcommon.utils.IntentUtils
import com.che.libcommon.utils.ToastUtils
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayout
import com.wswy.wzcx.R
import com.wswy.wzcx.model.ICity
import com.wswy.wzcx.model.WZCity
import com.wswy.wzcx.model.home.RPaths
import com.wswy.wzcx.model.home.RouterUtils
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.model.njdb.NjdbPreModel
import com.wswy.wzcx.model.wzdb.AddUserCertEntry
import com.wswy.wzcx.model.wzdb.classify
import com.wswy.wzcx.module.InternalMsgCode
import com.wswy.wzcx.module.base.CBaseLoadingFragment
import com.wswy.wzcx.module.base.getColor
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.car.choose.ChooseCityActivity
import com.wswy.wzcx.ui.data.Certs
import com.wswy.wzcx.ui.other.ClickUtils
import com.wswy.wzcx.ui.pay.PayNjdbData
import com.wswy.wzcx.ui.pay.PayOrder
import com.wswy.wzcx.ui.wzdb.CertCardSelectView
import com.wswy.wzcx.ui.wzdb.CertDataEntry
import com.wswy.wzcx.ui.wzdb.ChooseCertDialog
import com.wswy.wzcx.ui.wzdb.IInputView
import com.wswy.wzcx.utils.FileUtils
import com.wzcx.orclib.PhotoAgent
import kotlinx.android.synthetic.main.fragment_njdb_order.*
import timber.log.Timber
import java.io.File

/**
 * 年检代办
 */
class NjdbOrderFragment : CBaseLoadingFragment(), View.OnClickListener {

    override fun getConfigure(): ILoadingView.LoadingConfigure? = null

    override fun getLoadingFrameId() = R.id.rl_content


    companion object {
        const val TAG = "_NjdbOrderFragment"
        private const val REQ_CHOOSE_CITY = 501

        private const val REQ_PICK_GALLERY = 310

        private const val IMG_NAME = "img_njdb_"

        private const val ID_CARD_NAME = "njdb/%d/${IMG_NAME}%s.jpg"

    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_njdb_order
    }

    override fun getFragmentTitle(): String {
        return "完善资料"
    }


    private val deg = mutableMapOf<Int, Pair<CertCardSelectView, (Int, CertCardSelectView) -> Unit>>()

    private var currPath: String? = null
    private var currId: Int = 0

    private lateinit var userCarInfo: UserCarInfo

    private lateinit var njServiceViewModel: NjServiceViewModel

    private var currNjdbPayOrder: NjdbPreModel? = null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val carInfo = arguments?.getParcelable<UserCarInfo?>(Constants.EXTRA_DATA)
        if (carInfo == null) {
            finish()
            return
        }

        njServiceViewModel = provideViewModel(NjServiceViewModel::class.java)
        njServiceViewModel.onCreate()
        userCarInfo = carInfo

        fl_address.onClick {
            startActivityForResult(ChooseCityActivity.startPCityChoose(it.context), REQ_CHOOSE_CITY)
        }

        btn_submit.onClick {
            clickSubmit()
        }

        initData()
        initViews()

    }


    private fun initData() {

        njServiceViewModel.getUserLiveData().observe(this, Observer {
            it?.runCatching {
                et_user_phone.setText(this.mobile)
                et_user_name.requestFocus()
            }
        })

        njServiceViewModel.getPreOrder(userCarInfo.id).observe(this, Observer {
            it?.run {
                if (inLoading()) {
                    //加载中
                    showLoading(true)
                } else if (isOk() && data != null) {
                    //成功
                    currNjdbPayOrder = data
                    showData()
                } else if (hasError()) {
                    showError(VOMessage.create(null))
                }
            }

        })
        registerEvent(InternalMsgCode.CODE_PAY_SUCCESS) {
            finish()
        }

    }

    private fun initViews() {
        val photos = ArrayList<AddUserCertEntry>()
        photos.add(AddUserCertEntry("P", "行驶证正本正面照片", alias = "VLOF"))
        photos.add(AddUserCertEntry("Q", "行驶证副本正面照片", alias = "VLCF"))
        photos.add(AddUserCertEntry("Z1", "交强险照片", alias = "CLIVTA"))
        val layout = layout_certs
        val rowHeight = SizeUtils.dp2px(146f)
        val context = requireContext()
        var idN = 15200


        classify(photos).forEach {
            val titleLayout = LinearLayout(context).apply {
                orientation = LinearLayout.HORIZONTAL
                gravity = Gravity.CENTER_VERTICAL
            }

            val title = it.getTitle()

            val titleHint = when (it.type) {
                CertDataEntry.TYPE_VL -> SpannableStringBuilder().apply {
                    append("请填写")
                    append(SpannableString(userCarInfo.carNo).apply {
                        setSpan(ForegroundColorSpan(getColor(R.color.accentColor3)), 0, length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    })
                    append("的行驶证")
                }
                CertDataEntry.TYPE_USER_FACE -> "请上传车主本人自拍照，背景为纯色背景"
                else -> "请确保照片清晰"
            }

            val tvTitle = TextView(context).apply {
                text = title
                textSize = 16f
                setTextColor(getColor(R.color.textColorPrimary))
            }
            val tvTitleHint = TextView(context).apply {
                text = titleHint
                textSize = 12f
                setTextColor(getColor(R.color.textColorPrimary_40))
            }

            //标题
            titleLayout.addView(tvTitle)
            titleLayout.addView(tvTitleHint, ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT).apply {
                leftMargin = SizeUtils.dp2px(4f)
            })

            layout.addView(titleLayout, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(54f)))

            val imgContainer = FlexboxLayout(context).apply {
                flexWrap = FlexWrap.WRAP
            }

            layout.addView(imgContainer, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))

            it.list.forEachIndexed { index, addUserCertEntry ->
                val view = CertCardSelectView(context)
                view.id = ++idN
                view.bindEntry(index, addUserCertEntry)

                view.setOnClickListener(this)
                deg[view.id] = Pair(view, handlePhoto)

                val lp = FlexboxLayout.LayoutParams(0, rowHeight).apply {
                    flexGrow = 1f
                }

                if (index % 2 == 0) {
                    lp.isWrapBefore = true
                    lp.rightMargin = SizeUtils.dp2px(8f)
                } else {
                    lp.leftMargin = SizeUtils.dp2px(8f)
                }

//                    if (index/2 > 0 ){
//                        lp.topMargin = topM
//                    }
                imgContainer.addView(view, lp)
            }

            //填充空白
            if (it.list.size % 2 > 0) {
                val lp = FlexboxLayout.LayoutParams(0, rowHeight).apply {
                    leftMargin = SizeUtils.dp2px(8f)
                }
                lp.flexGrow = 1f
                imgContainer.addView(Space(context), lp)
            }

        }

//        val titleLayout = LinearLayout(context).apply {
//            orientation = LinearLayout.HORIZONTAL
//            gravity = Gravity.CENTER_VERTICAL
//        }
//
//        val tvTitle = TextView(context).apply {
//            text = getString(R.string.wzdb_notice_hint)
//            textSize = 13f
//            setTextColor(getColor(R.color.accentColor3))
//            setPadding(SizeUtils.dp2px(8f), SizeUtils.dp2px(5f), SizeUtils.dp2px(8f), SizeUtils.dp2px(5f))
//        }
//        tvTitle.setBackgroundColor(getColor(R.color.red_bg_color))
//        titleLayout.addView(tvTitle)
//        layout.addView(titleLayout, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, SizeUtils.dp2px(54f)))
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK && requestCode == REQ_CHOOSE_CITY) {

            val city = data?.getParcelableExtra<ICity>(Constants.EXTRA_DATA_CHOOSE_CITY)
            if (city is WZCity) {

                Timber.e("city  $city")
                tv_address_city.text = "${if (TextUtils.isEmpty(city.pname)) "" else "${city.pname}-"}${city.cityName}"
            }

        } else {
            if (requestCode == REQ_PICK_GALLERY) {
                currPath = File(IntentUtils.extraImageFromGallery(requireContext(), data)).absolutePath

                deg[currId]?.let {
                    it.second.invoke(requestCode, it.first)
                }
            } else {
                deg[requestCode]?.let {
                    it.second.invoke(requestCode, it.first)
                }
            }
        }

    }


    private val handlePhoto = fun(id: Int, view: CertCardSelectView) {


        var saveFile = if (TextUtils.isEmpty(currPath)) null else File(currPath)

        if (saveFile == null || !saveFile.exists()) {
            saveFile = FileUtils.getSaveFile(view.context, currPath)
        }


        saveFile?.let {

            if (it.exists()) {
                view.imgPath = it.absolutePath
            }

        }

    }


    private fun startPhoto(id: Int, path: String, key: String?) {

        val intent = PhotoAgent.getPhotoIntent(requireContext(), path, Certs.photoHints[key])

        startActivityForResult(intent, id)
    }

    private fun startGallery(id: Int, path: String, key: String?) {

//        startActivityForResult(IntentUtils.getPickGallery(), REQ_PICK_GALLERY)
        val intent = PhotoAgent.getPhotoIntent(requireContext(), path, Certs.photoHints[key], true)
        startActivityForResult(intent, id)

    }


    override fun onClick(v: View?) {
        if (ClickUtils.isFastClick()) {
            return
        }

        currPath = null
        v?.let { view ->

            val context = requireContext()

            val entry = deg[view.id]?.first?.certEntry

            val dialog = ChooseCertDialog(context, entry?.alias)
            dialog.onChooseListener = object : ChooseCertDialog.OnChooseListener {
                override fun onStartCamera() {

                    val pos = view.id
                    currPath = ID_CARD_NAME.format(userCarInfo.id, entry?.key)
                    FileUtils.getSaveFile(context, currPath)?.let {

                        startPhoto(pos, it.absolutePath, entry?.alias)
                    }

                }

                override fun onStartGallery() {
                    currId = view.id
//                    startGallery(view.id)
                    val pos = view.id
                    currPath = ID_CARD_NAME.format(userCarInfo.id, entry?.key)
                    FileUtils.getSaveFile(context, currPath)?.let {
                        startGallery(pos, it.absolutePath, entry?.alias)
                    }

                }

            }

            dialog.show()


        }

    }


    private fun clickSubmit() {
        val map = HashMap<String, String>()


        val name = et_user_name.text
        val phone = et_user_phone.text
        val city = tv_address_city.text
        val address = et_user_address.text

        if (TextUtils.isEmpty(name)) {
            ToastUtils.showText("请输入联系人姓名")
            return
        }

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showText("请输入联系电话")
            return
        }


        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showText("联系电话不正确，请重新输入")
            return
        }

        if (TextUtils.isEmpty(city)) {
            ToastUtils.showText("请选择城市")
            return
        }

        if (TextUtils.isEmpty(address)) {
            ToastUtils.showText("请输入详细地址")
            return
        }
        if (currNjdbPayOrder == null) {
            ToastUtils.showText("系统错误")
            return
        }

//        val files = NjdbUtils.getImgFiles(requireContext(),userCarInfo.id).mapKeys {
//            when(it.key){
//                "Z1" -> "compulsoryInsuranceCopy"
//                else -> it.key
//            }
//        }


        if (extraInput().isNullOrEmpty()) {
            return
        }

        val njdbData = PayNjdbData(name.toString(),
                phone.toString(),
                "$city-$address",
                userCarInfo.carNo,
                userCarInfo, currNjdbPayOrder!!)

        //先上传图片
        map["contacts"] = name.toString()
        map["mobile"] = phone.toString()
        map["address"] = "$city-$address"
        map["carNo"] = userCarInfo.carNo

        //map["payType"] = "${payLayout.getPayStyle().code}"

        RouterUtils.startPage(requireContext(), RPaths.PAY_ORDER, Bundle().apply {
            putParcelable(Constants.EXTRA_DATA, PayOrder(PayOrder.TYPE_NJDB, njdbData))
        })

    }

    private fun extraInput(): Map<String, Any>? {
        val datas = mutableMapOf<String, Any>()
        val views = arrayOf(layout_certs)
        views.forEach {
            if (it.isShown && !getValues(it, datas)) {
                return null
            }
        }
        return datas
    }


    private fun getValues(layout: ViewGroup, datas: MutableMap<String, Any>): Boolean {
        // 提取信息
        for (i in 0 until layout.childCount) {
            val childAt = layout.getChildAt(i)
            when (childAt) {
                is IInputView -> {

                    if (childAt.value == null || TextUtils.isEmpty(childAt.value?.toString())) {
                        ToastUtils.showText("请输入${childAt.info?.label}")
                        return false
                    }
                    childAt.info?.key?.let {
                        datas[it] = childAt.value
                    }
                }
                is FlexboxLayout -> {

                    for (j in 0 until childAt.childCount) {
                        val childAtPhoto = childAt.getChildAt(j)

                        if (childAtPhoto is IInputView) {

                            if (childAtPhoto.value == null || (childAtPhoto.value is File && !(childAtPhoto.value as File).exists())) {
                                ToastUtils.showText("请输入${childAtPhoto.info?.label}")
                                return false
                            }
                            childAtPhoto.info?.key?.let {
                                datas[it] = childAtPhoto.value
                            }
                        }
                    }
                }
            }

        }
        return true
    }


}